var _that;
var timeId;
var app = getApp();
var {getNodeRef, keepTwoDecimalFull} = require('../../utils/util')

function carInit(target, _goodslist = [], _goodsidlist = []) {
  _that = target;
  _that.setData({
    cartype: 'cake',
    showCartCnt: false,
    showCart: false,
    cartAdded: false,
    cartFly: false,
    curCartImg: '',
    flyStyle: {},
    flyInStyle: {}
  });

  loadCarData(_goodslist, _goodsidlist);
}

function showDetail() {
  if (_that.data.totalcount <= 0) {
    return
  }
  _that.setData({
    showCart: true
  })
  _that.setData({
    showCartCnt: true
  })
}

function closeDetail() {
  _that.setData({
    showCartCnt: false
  })
  setTimeout(() => {
    _that.setData({
      showCart: false
    })
  }, 300)
}

function toggleDetail () {
  if (_that.data.showCart) {
    closeDetail()
  } else {
    showDetail()
  }
}

function update() {

}

function submitOrder(orderinfo) {
  if (_that.data.address == null || _that.data.address === undefined) {
    if(app.globalData.address !=null && app.globalData.address !== undefined){
      _that.setData({
        address: app.globalData.address
      });
    } else {
      app.toast.error('请先添加收货地址！')
      setTimeout(() => {
        wx.switchTab({
          url: '../../my/myindex'
        });
      }, 1000);
      return;
    }
  }
  if (_that.data.totalcount <= 0) {
    return;
  }
  var orderinfo = {
    mid: _that.data.mid,
    fid: _that.data.fid,
    stationId: _that.data.stationId,
    goodslist: _that.data.goodslist
  }
  wx.navigateTo({
    url: `../../neworder/neworder?type=cake&orderinfo=${encodeURIComponent(JSON.stringify(orderinfo))}&address=${encodeURIComponent(JSON.stringify(_that.data.address))}`
  })
}

function startBounce() {
  _that.setData({
    cartAdded: true
  })

  if (timeId) {
    clearTimeout(timeId);
  }
  timeId = setTimeout(() => {
    _that.setData({
      cartAdded: false
    })
  }, 1000)
}

function startFly(id, imgUrl) {
  if (_that.data.cartFly) return;

  Promise.all([getNodeRef(id), getNodeRef("#cart_icon")]).then( values => {
    var addNodeRef = values[0];
    var cartNOdeRef = values[1]
    _that.setData({
      cartFly: true,
      curCartImg: imgUrl,
      flyStyle: {
        left: addNodeRef.left,
        top: addNodeRef.top
      }
    })

    _that.setData({
      flyStyle: {
        left: addNodeRef.left,
        top: addNodeRef.top,
        transform: 'translate3d(0,' + (cartNOdeRef.top - addNodeRef.top) + 'px,0)'
      },
      flyInStyle: {
        transform: 'translate3d(' + (cartNOdeRef.left - addNodeRef.left + 8) + 'px,0,0)',
        width: 10,
        height: 10
      }
    })

    setTimeout(() => {
      startBounce()
      _that.setData({
        cartFly: false,
        curCartImg: '',
        flyStyle: {},
        flyInStyle: {}
      })
    }, 800);

  })
}

function handleCount(e) {
  var options, goodsid;
  if (e.currentTarget) {
    options = parseInt(e.currentTarget.dataset.options);
    goodsid = e.currentTarget.dataset.goodsid;
  }
  else {
    options = e.options;
    goodsid = e.goodsid;
  }
  var goodslist = _that.data.goodslist;
  var goodsidlist = _that.data.goodsidlist;
  var totalcount = parseInt(_that.data.totalcount);
  var totalprice = parseFloat(_that.data.totalprice);
  var curIndex = goodsidlist.indexOf(goodsid);

  if (Number(options) === 1) {
    var num = 1;
    if (e.num) {
      num = parseInt(e.num);
    }
    totalcount += num;
    if (curIndex >= 0) {
      goodslist[curIndex].num = parseInt(goodslist[curIndex].num) + num;
      goodslist[curIndex].COUNT = parseInt(goodslist[curIndex].COUNT) + num;
      totalprice += parseFloat(goodslist[curIndex].price) * num;
      startFly('#addcart', goodslist[curIndex].image)
    }
    else {
      totalprice += parseFloat(e.price) * num;
      goodsidlist.push(goodsid);
      goodslist.push({
        goodsid: goodsid,
        ID: goodsid,
        num: num,
        COUNT: num,
        name: e.name,
        shortname: e.shortname,
        price: e.price,
        img: e.img,
        image: e.image,
        icon: e.icon,
        sku: e.sku,
        spec: e.spec,
        size: e.size,
        tips: e.tips
      });
      startFly('#addcart', e.image)
    }
  }
  else {
    if (totalcount > 0 && curIndex >= 0) {
      totalcount -= 1;
      totalprice -= parseFloat(goodslist[curIndex].price);
      goodslist[curIndex].num = parseInt(goodslist[curIndex].num) - 1;
      goodslist[curIndex].COUNT = parseInt(goodslist[curIndex].COUNT) - 1;
      if (parseInt(goodslist[curIndex].num) <= 0) {
        goodslist.splice(curIndex, 1);
        goodsidlist.splice(curIndex, 1);
      }
    }
  }

  totalprice = keepTwoDecimalFull(totalprice);
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: goodslist,
    goodsidlist: goodsidlist
  });

  if (totalcount === 0) {
    _that.setData({
      needshow: false
    });
  }
}

module.exports = {
  init: carInit,
  showCar: showDetail,
  closeCar: closeDetail,
  toggleCar: toggleDetail,
  update: update,
  submitOrder: submitOrder,
  handleCount: handleCount
}

//------以下方法不外调
function loadCarData(_goodslist = [], _goodsidlist = []) {
  var totalcount = 0;
  var totalprice = 0.00;
  var num = 0;
  for (var i = 0; i < _goodslist.length; i++) {
    num = parseInt(_goodslist[i].num);
    totalcount += num;
    totalprice += parseFloat(_goodslist[i].price) * num;
  }
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: _goodslist,
    goodsidlist: _goodsidlist
  });
}
